package org.ee.iris.server;

import io.netty.channel.*;
import java.util.concurrent.ConcurrentHashMap;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    // 保存所有连接的客户端通道
    private static final ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String id = ctx.channel().id().asShortText();
        channels.put(id, ctx.channel());
        broadcast("用户 " + id + " 加入聊天");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        String id = ctx.channel().id().asShortText();
        channels.remove(id);
        broadcast("用户 " + id + " 离开聊天");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        String id = ctx.channel().id().asShortText();
        broadcast("[" + id + "]: " + msg);
    }

    private void broadcast(String message) {
        for (Channel ch : channels.values()) {
            ch.writeAndFlush(message + "\n");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
